var express = require('express');
var router = express.Router();
var jiami = require('../../module/jiami');
var sqlQuery = require('../../module/sql')

var user = require('./user/user');
var category = require('./category/category');
var film = require('./film/film');
var nav = require('./nav/nav');
var slide = require('./slide/slide');



//判断是否符合进入后台
function permisson(req,res,next){
  if(req.session.username == undefined){
    //还没有登陆,返回到登陆页面
    res.render('info/info',{
      title:"没有登陆",
      content:"请登录，即将进入登陆页面",
      href:"/rl/login",
      hrefTxt:"登录页"
    })
  }else{
    //正常进入
    next()
  }
}


router.get('/', permisson, async(req, res, next)=> {
  // console.log("用户名：",req.session.username)
  
  res.render('admin/index',{username:req.session.username})
});

router.get('/welcome',async(req, res, next)=> {
  res.render('admin/welcome')
});


router.get('/welcome/api',async(req, res, next)=> {
  let sqlStr = 'SELECT type.typeName,count(1) AS counts FROM film,type where film.Typeid = type.id GROUP BY type.typeName';
  let result = await sqlQuery(sqlStr)
  res.json(result)
});






// //设置后台权限的中间件
// async function adminAuth(req,res,next){
//   //通过用户名查找角色的id   就是 roleid
//   //'select roleid from user where username = ?'
//   //通过id  查找角色的权限
//   //'select authid from role_auth where roleid = ?'
//   //通过权限id 获取允许访问地址
//   //'select * from auth where id in (select authid from role_auth where roleid = (select roleid from user where username = ?))'

//   //获取登录后的用户名
//   let username = req.session.username;

//   //通过用户名查看允许访问的地址
//   let sqlStr = 'select * from auth where id in (select authid from role_auth where roleid = (select roleid from user where username = ?))'
//   let result = await sqlQuery(sqlStr,[username]);
//   // 转换成数组
//   let resultArr = Array.from(result);

//   //判断当前访问地址是否允许的地址
//   let httpUrl = req.originalUrl;  //获取当前访问地址   根目录
//   //判断当前访问地址是否在允许的数组里面
//   let isAllow = resultArr.some((item,i)=>{
//     return new RegExp("^"+item.authurl).test(httpUrl);
//   })
//   if(isAllow){
//     //如果允许访问,正常进入
//     next()
//   }else{
//     //如果不允许访问
//     res.render('info/info',{
//       title:"禁止访问",
//       content:"没有权限访问该页面！",
//       href:"/",
//       hrefTxt:"首页"
//     })
//   }

//}









//设置后台权限的中间件
// router.use(adminAuth)
router.use('/user',user);
router.use('/category',category);
router.use('/film',film);
router.use('/nav',nav);
router.use('/slide',slide);





module.exports = router;
